// 食品列表
import { LoadingOutlined, PlusOutlined, RightOutlined, DownOutlined } from '@ant-design/icons';
import {
    Table, Descriptions,
    Button, Form, Input, Select,
    message, Upload,
    Modal,
    Popconfirm,
    Space, Tag,
} from 'antd';

import type { UploadChangeParam } from 'antd/es/upload';
import type { RcFile, UploadFile, UploadProps } from 'antd/es/upload/interface';

import type { ColumnsType } from 'antd/es/table';
import React from 'react';
import { foodCount, foodList, foodClass, updateFood, deleteFood } from '../../api/request';
import { useEffect, useState } from 'react';

import { render } from '@testing-library/react';
import { log } from 'console';
import { text } from 'stream/consumers';

// import { PlusOutlined } from '@ant-design/icons';
// import "./AdminFoods.css";

// 弹窗
const { Option } = Select;
const layout = {
    labelCol: { span: 8 },
    wrapperCol: { span: 16 },
};
const tailLayout = {
    wrapperCol: { offset: 8, span: 16 },
};

// 上传图片
const getBase64 = (img: RcFile, callback: (url: string) => void) => {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result as string));
    reader.readAsDataURL(img);
};

const beforeUpload = (file: RcFile) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
        message.error('您只能上传 JPG/PNG 格式!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
        message.error('图片不能超过 2MB!');
    }
    return isJpgOrPng && isLt2M;
};


const add = (record: any) => (
    <Descriptions column={2}>
        <Descriptions.Item label="食品名称">{record.name}</Descriptions.Item>
        <Descriptions.Item label="食品 ID">{record.item_id}</Descriptions.Item>
        <Descriptions.Item label="食品介绍">{record.description}</Descriptions.Item>
        <Descriptions.Item label="食品评分">{record.rating}</Descriptions.Item>
        <Descriptions.Item label="月销量">{record.month_sales}</Descriptions.Item>
        <Descriptions.Item label="餐馆名称">{ }</Descriptions.Item>
        <Descriptions.Item label="餐馆 ID">{record.restaurant_id}</Descriptions.Item>
        <Descriptions.Item label="餐馆地址">{ }</Descriptions.Item>
        <Descriptions.Item label=" 食品分类">{ }</Descriptions.Item>
    </Descriptions>
)


// 修改商品信息底部内容
interface DataType {
    key: string;
    name: string;
    age: number;
    address: string;
    tags: string[];
}

const col: ColumnsType<DataType> = [
    {
        title: '规格',
        dataIndex: 'specs',
    },
    {
        title: '包装费',
        dataIndex: 'packing_fee',
    },
    {
        title: '价格',
        dataIndex: 'price',
    },
    {
        title: '操作',
        render: (_, record) => (
            <Space size="middle">
                <a>删除</a>
            </Space>
        ),
    },
];

const colDate: any = [{
    specs: "默认",
    packing_fee: 0,
    price: 20
}]

const App: React.FC = () => {
    let inFifteenMinutes = new Date(new Date().getTime() + 24 * 3600 * 1000)
    // 食品分类
    // console.log(cookie.load("SID"));

    const [foodclass, setFoodClass] = useState([])
    const [open, setOpen] = useState(false);

    const [names, setNames] = useState("")
    const [description, setDescription] = useState("")
    const [category_name, setCategory_name] = useState("")
    const [imgPath, setImgPath] = useState()
    const [foodId, setFoodId] = useState()
    const [cateId, setCateId] = useState()

    const getId = (text: any, record: any) => {
        setOpen(true)
        setFoodId(text)
        setCateId(record.category_id)
        setNames(record.name)
        setDescription(record.description)
        setCategory_name(record.category_name)
        setImgPath(record.image_path)
    }
    const deletId = (text: any, record: any) => {
        deleteFood(text).then(res => {
            console.log(res);
            if (res.status == 0) {
                message.error(res.message)
            }
        })
    }

    const cancel = () => {
        setOpen(false)
        setNames("")
        setDescription("")
        setCategory_name("")
        window.location.reload()
    }
    const columns = [
        { title: '食品名称', dataIndex: 'name' },
        { title: '食品介绍', dataIndex: 'description' },
        { title: '评分', dataIndex: 'rating' },
        {
            title: '编辑',
            dataIndex: 'item_id',
            render: (text: any, record: any) => {
                return (
                    <Button onClick={() => { getId(text, record) }} size="small">
                        编辑
                    </Button>
                )
            }
        },
        {
            title: '删除',
            dataIndex: '',
            key: 'x',
            render: (text: any, record: any) => {
                return (
                    <>
                        {/* <Popconfirm title="确定删除吗?" okText="Yes" cancelText="No" onConfirm={()=>{deleteFood(foodId)}}>
                            <Button>删除</Button>
                        </Popconfirm> */}
                        <Button onClick={() => { deletId(text, record) }} size="small" danger>删除</Button>
                    </>
                )
            },
        },
    ];

    const [data, setData] = useState([])
    const [count, setCount] = useState()
    //当前页
    const [Page, setPage] = useState(0)
    //每页条数
    const [PageSize, setPageSize] = useState(20)

    const onChange = (page: number, pageSize: number) => {
        setPage(() => page)
        setPageSize(() => pageSize)
    }

    // 修改弹窗底部内容
    const [coldata, setColData] = useState([])


    useEffect(() => {
        foodList({
            offset: Page,
            limit: PageSize
        }).then((res) => {
            // console.log(res.data);
            setData(() => res.data)
        })
        foodCount().then((res) => {
            // console.log(res);
            setCount(() => res.data.count)
        })
        foodClass().then(res => {
            // console.log(res.data);
            setFoodClass(() => res.data)
        })

    }, [Page, PageSize])


    // 弹窗
    const [form] = Form.useForm();

    const onFinish = (values: any) => {
        cancel()
        console.log(values);
        console.log(foodId, colDate, cateId, cateId);
        const data = {
            name: values.name,
            category_name: values.category_name,
            item_id: foodId,
            specs: colDate,
            image_path: imageUrl,
            category_id: cateId,
            new_category_id: cateId,
            description: values.description
        }
        console.log(data);

        updateFood(
            data
        ).then((res: any) => {
            // console.log(res);
            if (res.status == 1) {
                message.success(res.success)
                window.location.reload()
            } else if (res.status == 0) {
                message.error(res.message)
                setOpen(false)
            }

        })

    };


    const onFill = () => {
        form.setFieldsValue({
            note: 'Hello world!',
            gender: 'male',
        });
    };


    // 上传图片
    const [loading, setLoading] = useState(false);
    const [imageUrl, setImageUrl] = useState<string>();

    const handleChange: UploadProps['onChange'] = (info: UploadChangeParam<UploadFile>) => {
        if (info.file.status === 'uploading') {
            setLoading(true);
            return;
        }
        if (info.file.status === 'done' && info.file.response) {
            // Get this url from response in real world.
            getBase64(info.file.originFileObj as RcFile, url => {
                setLoading(false);
                setImageUrl(info.file.response.image_path);
            });
        }
    };

    const uploadButton = (
        <div>
            {loading ? <LoadingOutlined /> : <PlusOutlined />}
            <div style={{ marginTop: 8 }}>Upload</div>
        </div>
    );

    return (
        <> <Table
            columns={columns}
            expandable={{
                expandedRowRender: record => add(record),
                expandIcon: ({ expanded, onExpand, record }) =>
                    expanded ? (
                        <DownOutlined onClick={e => onExpand(record, e)} />
                    ) : (
                        <RightOutlined onClick={e => onExpand(record, e)} />
                    )
            }}
            dataSource={data}
            scroll={{ y: 430 }}
            pagination={
                {
                    total: count,
                    pageSize: PageSize,
                    onChange: (page, pageSize) => {
                        onChange(page, pageSize)
                    }
                }
            }
            rowKey={(render: any) => render.tips}

        />

            <Modal
                title="修改食品信息"
                centered
                open={open}
                onCancel={() => cancel()}
                width={500}
                footer={null}

            >
                <Form {...layout} form={form} name="control-hooks" onFinish={onFinish} onFinishFailed={() => { cancel() }} initialValues={{
                    name: names,
                    description: description,
                    category_name: category_name
                }}>
                    <Form.Item name="name" label="食品名称" rules={[{ required: true }]}>
                        <Input />
                    </Form.Item>
                    <Form.Item name="description" label="食品介绍" rules={[{ required: true }]}>
                        <Input />
                    </Form.Item>
                    <Form.Item name="category_name" label="食品分类" rules={[{ required: true }]}>
                        <Select
                            placeholder="甜品饮品"
                            // onChange={onGenderChange}
                            allowClear
                        >
                            {
                                foodclass.map((item: any, index: number) => <Option value={item.title} key={'name' + index}>{item.title}</Option>)
                            }

                        </Select>
                    </Form.Item>
                    <Form.Item label="食品图片">
                        <Upload
                            name="file"
                            listType="picture-card"
                            className="avatar-uploader"
                            showUploadList={false}
                            action="/v1/addimg/food"
                            beforeUpload={beforeUpload}
                            onChange={handleChange}
                            style={{
                                overflow: "hidden"
                            }}
                        >
                            <img src={imageUrl ?"//elm.cangdu.org/img/" + imageUrl:"//elm.cangdu.org/img/" + imgPath} alt="avatar" style={{
                                width: 120,
                                height: 100,
                                display: "block"
                            }} />
                        </Upload>
                    </Form.Item>
                    <Table
                        columns={col}
                        dataSource={colDate}
                        rowKey={(render: any) => render.specs}
                        pagination={false}
                    />
                    <Form.Item
                        noStyle
                        shouldUpdate={(prevValues, currentValues) => prevValues.gender !== currentValues.gender}
                    >
                        {({ getFieldValue }) =>
                            getFieldValue('gender') === 'other' ? (
                                <Form.Item name="customizeGender" label="Customize Gender" rules={[{ required: true }]}>
                                    <Input />
                                </Form.Item>
                            ) : null
                        }
                    </Form.Item>

                    <Form.Item {...tailLayout}>
                        <Button type="primary" htmlType="submit" style={{ margin: 10 }}>
                            提交
                        </Button>
                        <Button style={{ margin: 10 }} onClick={() => { cancel() }}>
                            取消
                        </Button>
                    </Form.Item>
                </Form>

            </Modal>

        </>





    );
}

export default App;